package com.pay.paytoken.fragment;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.pay.paytoken.BuildConfig;
import com.pay.paytoken.R;
import com.pay.paytoken.activity.HelpActivity;
import com.pay.paytoken.activity.lock.LockManager;
import com.pay.paytoken.base.BaseFragment;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import apiUtils.apis.GetDataTimeAPI;
import apiUtils.apis.GetVersionsAPI;
import apiUtils.models.VersionModel;
import appUtils.CustomAlertDoubleBtnDialog;
import appUtils.LogUtil;
import appUtils.PayTokenException;
import appUtils.PhoneUtil;
import appUtils.PopupWindowUtil;
import appUtils.ToastUtil;
import appUtils.VersionUpdate;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import totpUtils.SPUtils;

import static constant.ApiConstants.TASK_SUCCESS;
import static totpUtils.config.MTokenConstants.PREFS_SERVICE_TIME_REDUCE;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainSettingFragment extends BaseFragment implements LockManager.LockObserver, View.OnClickListener {

    private static final int CHECKCODE = 1;
    private static final int ABOUTTOKEN = 2;
    @Bind(R.id.layout_title_iv_left)
    ImageButton mLayoutTitleIvLeft;
    @Bind(R.id.layout_title_textName)
    TextView mLayoutTitleTextName;
    @Bind(R.id.layout_title_ivSecond)
    ImageButton mLayoutTitleIvSecond;
    @Bind(R.id.layout_title)
    AutoLinearLayout mLayoutTitle;
    @Bind(R.id.rl_setting_timeCalibration)
    AutoRelativeLayout mRlSettingTimeCalibration;
    @Bind(R.id.rl_setting_clearCache)
    AutoRelativeLayout mRlSettingClearCache;
    @Bind(R.id.rl_setting_shareToFriends)
    AutoRelativeLayout mRlSettingShareToFriends;
    @Bind(R.id.rl_setting_lookCode)
    AutoRelativeLayout mRlSettingLookCode;
    @Bind(R.id.rl_setting_checkUpdate)
    AutoRelativeLayout mRlSettingCheckUpdate;
    @Bind(R.id.rl_setting_about)
    AutoRelativeLayout mRlSettingAbout;
    @Bind(R.id.check_for_updates_version)
    TextView mCheckForUpdatesVersion;
    @Bind(R.id.tv_time_now)
    TextView mTvTimeNow;
    @Bind(R.id.gesture_switch)
    ImageButton mGestureSiwtch;
    @Bind(R.id.fingerprint_switch)
    ImageButton mFingerPrintSwitch;
    @Bind(R.id.fingerprint_layout)
    AutoRelativeLayout mFingerPrintLayout;
    @Bind(R.id.gesture_layout)
    AutoRelativeLayout mGestureLayout;
    @Bind(R.id.set_gesture_code_linear_layout)
    AutoLinearLayout mSetGestureLayout;
    @Bind(R.id.check_for_updates_next)
    ImageView mCheckForUpdatesNext;
    @Bind(R.id.rl_setting_help)
    AutoRelativeLayout mRlSettingHelp;
    private Context mContext;
    private Handler mHandler;
    private VersionUpdate mVersionUpdate;
    private CustomAlertDoubleBtnDialog mDialog;
    private String mUrl;
    private String[] mPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    public int setView() {
        return R.layout.fragment_main_bottom_fragment2;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mContext = getContext();
        mVersionUpdate = new VersionUpdate(mContext);
        mDialog = new CustomAlertDoubleBtnDialog(getActivity());
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        try {
                            long time = System.currentTimeMillis() / 1000 + msg.arg1;
                            @SuppressLint("SimpleDateFormat")
                            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                            String timeString = df.format(new Date(time * 1000L));
                            mTvTimeNow.setText(timeString);
                        } catch (ParseException e) {
                            e.printStackTrace();
                            PayTokenException.getInstance().saveExceptionFile("MainSettingFragment " +
                                    "ParseException error:" + e.getMessage());
                        }
                        int arg2 = msg.arg2;
                        if (arg2 == 1) {
                            ToastUtil.showShort(R.string.time_calibration_success);
                        }
                        break;
                    case 1:
                        ToastUtil.showShort(R.string.time_calibration_error);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public void initView() {

        mLayoutTitleIvLeft.setVisibility(View.INVISIBLE);
        mLayoutTitleTextName.setText(R.string.home_bottom_text2);

        setSettingPattern();

        //set Version code
        mCheckForUpdatesVersion.setText("V " + BuildConfig.VERSION_NAME);

//        if (LockManager.getInstance().getHasFingerprintAU()) {
//            mGestureLayout.setVisibility(View.GONE);
//            mSetGestureLayout.setVisibility(View.GONE);
//        } else {
//            mFingerPrintLayout.setVisibility(View.GONE);
//        }

        LockManager.getInstance().attachObserver(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mGestureSiwtch.setImageResource(LockManager.getInstance().getGestureAble() ? R.drawable.icon_setting_open : R.drawable.icon_setting_close);
        mFingerPrintSwitch.setImageResource(LockManager.getInstance().getFingerprintAble() ? R.drawable.icon_setting_open : R.drawable.icon_setting_close);
    }

    private void setSettingPattern() {
        mGestureSiwtch.setOnClickListener(this);
        mFingerPrintSwitch.setOnClickListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.reset_lock_code_layout, R.id.rl_setting_timeCalibration, R.id.rl_setting_clearCache,
            R.id.rl_setting_shareToFriends, R.id.rl_setting_lookCode, R.id.rl_setting_checkUpdate, R.id.rl_setting_about, R.id.rl_setting_help})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.reset_lock_code_layout:
                reSetCodeLock();
                break;
            case R.id.rl_setting_timeCalibration:
                reSetTime(1);
                break;
            case R.id.rl_setting_clearCache:
                break;
            case R.id.rl_setting_shareToFriends:
                break;
            case R.id.rl_setting_lookCode:
                String deviceId = PhoneUtil.getDeviceId(getContext());
                if (!TextUtils.isEmpty(deviceId)) {
                    String about = getResources().getString(R.string.number, deviceId);
                    PopupWindowUtil.showLookCodeDialog(getActivity(), R.style.style_dialog, R.layout.popview_popupwindow, getString(R.string.notice_1),
                            getString(R.string.notice_2), about, null, CHECKCODE);
                }
                break;
            case R.id.rl_setting_checkUpdate:
                checkUpdate();
                break;
            case R.id.rl_setting_about:
                PopupWindowUtil.showLookCodeDialog(getActivity(), R.style.style_dialog, R.layout.popview_popupwindow, null, null, null,
                        BuildConfig.VERSION_NAME, ABOUTTOKEN);
                break;
            case R.id.rl_setting_help:
                startActivity(new Intent(mActivity, HelpActivity.class));
                break;
            default:
                break;
        }
    }

    private void checkUpdate() {
        showProgress(R.string.loadding);
        final String nowVersion = mVersionUpdate.getCurrentVersion();
        new GetVersionsAPI(mContext).getVersionsAPI(nowVersion, new GetVersionsAPI.Listener() {
            @Override
            public void onSuccess(final VersionModel model) {
                if (null != model) {
                    if (!TextUtils.isEmpty(model.getState())) {
                        if (TASK_SUCCESS.equals(model.getState())) {
                            if (!TextUtils.isEmpty(model.getNewVersion()) && !TextUtils.isEmpty(model.getUrl())) {
                                dismisProgress();
                                mUrl = model.getUrl();
                                isUpdate(nowVersion, model.getNewVersion(), mUrl);
                            }
                        } else {
                            dismisProgress();
                            ToastUtil.showShort(R.string.latest_version);
                        }
                    }
                }
                LogUtil.log("checkUpdate Success");
            }

            @Override
            public void onFailure(int code, String msg) {
                dismisProgress();
                if (!TextUtils.isEmpty(msg)) {
                    ToastUtil.showShort(msg);
                } else {
                    ToastUtil.showShort(R.string.check_network);
                }
                LogUtil.log("checkUpdate  onFailure");
            }
        });

    }

    private void isUpdate(String nowVersion, String newVersion, final String url) {
        mDialog.setTitle(getString(R.string.dialog_update_title));
        mDialog.setRightBtnLabel(getString(R.string.upgrade_now));
        mDialog.setLeftBtnLabel(getString(R.string.talk_to_you_later));
        mDialog.setMsg("\u3000" + getString(R.string.down_version, nowVersion, newVersion));
        CustomAlertDoubleBtnDialog.commitClickListener listener = new CustomAlertDoubleBtnDialog.commitClickListener() {
            @Override
            public void onClick() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
                    int checkPermission = mContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                1);
                    } else {
                        mVersionUpdate.downloadVersion(url);
                    }

                } else {
                    mVersionUpdate.downloadVersion(url);
                }
            }
        };
        mDialog.setCommitClickListener(listener);
        mDialog.showDialog();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mVersionUpdate.downloadVersion(mUrl);
                } else {
                    showPermissionDialog();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    /**
     * 不再提示权限 时的展示对话框
     **/
    private void showPermissionDialog() {
        mDialog.setTitle(getString(R.string.setting));
        mDialog.setMsg(getString(R.string.please_awarded_to_store_permissions_manually));
        mDialog.setRightBtnLabel(getString(R.string.confirm));
        mDialog.setLeftBtnLabel(getString(R.string.abrogate));
        mDialog.setCancelAble(false);
        CustomAlertDoubleBtnDialog.commitClickListener commitClickListener =
                new CustomAlertDoubleBtnDialog.commitClickListener() {
                    @Override
                    public void onClick() {
                        goSetting();
                    }
                };
        mDialog.setCommitClickListener(commitClickListener);
        mDialog.showDialog();
    }

    /**
     * go SettingActivity to icon_password_open permission
     */
    private void goSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        localIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
        startActivity(localIntent);
    }


    /**
     * Reset the icon_password if signal switch is open, need to verify the icon_password to reset the success
     * Reset the icon_password if the gesture switch is open, you need to verify the icon_password can be reset successfully
     */
    private void reSetCodeLock() {
        LockManager.getInstance().updateDigitalLock(mContext);
    }

    public void reSetTime(final int i) {
        showProgress(R.string.loadding);
        new GetDataTimeAPI().getServerTime(new GetDataTimeAPI.Listener() {
            @Override
            public void onSuccess(long deltaTime) {
                dismisProgress();
                SPUtils.put(PREFS_SERVICE_TIME_REDUCE, deltaTime * 1000);
                Message message = new Message();
                message.what = 0;
                message.arg1 = (int) deltaTime;
                message.arg2 = i;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(int code) {
                dismisProgress();
                mHandler.sendEmptyMessage(1);
            }
        });
    }

    @Override
    public void onLockChangeCallBack(int index, boolean able) {
        switch (index) {
            case LockManager.FINGERPRINT:
                mFingerPrintSwitch.setImageResource(able ? R.drawable.icon_setting_open : R.drawable.icon_setting_close);
                break;
            case LockManager.GESTURE:
                mGestureSiwtch.setImageResource(able ? R.drawable.icon_setting_open : R.drawable.icon_setting_close);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.gesture_switch:
                if (LockManager.getInstance().getGestureAble()) {
                    LockManager.getInstance().updateGesture(mContext, 2);
                } else {
                    ToastUtil.showShort(R.string.please_set_gesture_lock);
                }
                break;
            case R.id.fingerprint_switch:
                LockManager.getInstance().setFingerprintAble(mContext, !LockManager.getInstance().getFingerprintAble());
                break;
        }
    }

    @OnClick(R.id.set_gesture_code_layout)
    protected void setGesture() {
        LockManager.getInstance().updateGesture(mContext, 4);
    }
}
